import { defineStore } from 'pinia';
import type { RouteRecordNormalized } from 'vue-router';
import defaultSettings from '@/config/settings.json';
import { AppState } from './types';
import router from '@/router';
import { DEFAULT_LAYOUT } from '@/router/routes/base';
import { menuListTreeTest } from '@/api/menu';
import { getMenuName, getMenuStorage, getRouterName, setMenuStorage } from '@/utils/auth';
import componentMap from '@/router/constants';

const useAppStore = defineStore('app', {
  state: (): AppState => ({ ...defaultSettings }),

  getters: {
    appCurrentSetting(state: AppState): AppState {
      return { ...state };
    },
    appDevice(state: AppState) {
      return state.device;
    },
    appAsyncMenus(state: AppState): RouteRecordNormalized[] {
      return state.serverMenu as unknown as RouteRecordNormalized[];
    },
  },

  actions: {
    // Update app settings
    updateSettings(partial: Partial<AppState>) {
      // @ts-ignore-next-line
      this.$patch(partial);
    },

    // Change theme color
    toggleTheme(dark: boolean) {
      if (dark) {
        this.theme = 'dark';
        document.body.setAttribute('arco-theme', 'dark');
      } else {
        this.theme = 'light';
        document.body.removeAttribute('arco-theme');
      }
    },
    toggleDevice(device: string) {
      this.device = device;
    },
    toggleMenu(value: boolean) {
      this.hideMenu = value;
    },
    async fetchServerMenuConfig() {
      const menuStorage: any = getMenuStorage() || null
      try {
        let res: any
        if (menuStorage) {
          res = {
            code: 1,
            data: JSON.parse(menuStorage)
          }
        }
        else {
          res = await menuListTreeTest({})
        }
        if (res?.code === 1) {
          setMenuStorage(JSON.stringify(res?.data))
          const menuList: any = [
            {
              path: '/home',
              name: 'home',
              meta: {
                locale: 'menu.home',
                requiresAuth: true,
                icon: 'icon-user',
                order: 0,
              },
              children: [
                {
                  path: '/home/index',
                  name: 'HomeIndex',
                  meta: {
                    locale: 'menu.home',
                    requiresAuth: true,
                    roles: ['*'],
                  },
                },
              ],
            }
          ]
          res?.data?.forEach((item: any) => {
            let i: any = {
              path: item?.web_url,
              name: getMenuName(item?.web_url),
              meta: {
                locale: item?.name,
                requiresAuth: true,
                order: 0,
              },
              component: DEFAULT_LAYOUT,
              children: []
            }
            item?.children?.forEach((itz: any) => {
              if (itz?.web_url === '/institution/institution') { itz.web_url = '/institution/institutionManagement' }
              if (itz?.web_url === '/mediators/user') { itz.web_url = '/mediators/mediatorsUser' }
              if (itz?.web_url === '/impartial/user') { itz.web_url = '/impartial/impartialUser' }
              const componentKeyValue: any = getRouterName(itz?.web_url)
              i.children.push({
                path: itz?.web_url,
                name: getMenuName(itz?.web_url),
                meta: {
                  locale: itz?.name,
                  requiresAuth: true,
                  order: 0,
                },
                component: () => componentKeyValue ? componentMap?.[componentKeyValue?.key]?.[componentKeyValue?.value] : null,
              })
            })
            menuList.push(i)
            router.addRoute(i)
          })
          this.serverMenu = menuList;
        }
        else {
          this.serverMenu = []
        }
      } catch (error) {
      }
    },
    clearServerMenu() {
      this.serverMenu = [];
    },
  },
});

export default useAppStore;
